﻿using Base.ModuleBase.RoutedCommands;
using Prism.Common;
using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;

namespace Base.ModuleBase.Behaviors
{
    public class PopWindowCmdBindingBehavior : Behavior<Window>
    {
        protected override void OnAttached()
        {
            base.OnAttached();
            BindPopWindowCmds();
        }

        private void BindPopWindowCmds()
        {
            var cmdbing = new CommandBinding(PopupWindowCommands.Maximum, (s, e) =>
            {
                if (Dispatcher.CheckAccess())
                {

                    ToMaxOrNormalWindow();
                }
                else
                {
                    Dispatcher.Invoke(new Action(ToMaxOrNormalWindow));
                }
            });
            AssociatedObject.CommandBindings.Add(cmdbing);

            cmdbing = new CommandBinding(PopupWindowCommands.Minimum, (s, e) =>
            {
                if (Dispatcher.CheckAccess())
                {
                    AssociatedObject.WindowState = WindowState.Minimized;
                }
                else
                {
                    Dispatcher.Invoke(new Action(() => { AssociatedObject.WindowState = WindowState.Minimized; }));
                }
            });
            AssociatedObject.CommandBindings.Add(cmdbing);

            cmdbing = new CommandBinding(PopupWindowCommands.Close, (s, e) =>
            {
                if (Dispatcher.CheckAccess())
                {
                    CloseWindow();
                }
                else Dispatcher.Invoke(new Action(CloseWindow));
            });
            AssociatedObject.CommandBindings.Add(cmdbing);
        }

        private void CloseWindow()
        {
            MvvmHelpers.ViewAndViewModelAction<PopWindowViewModelBase>(AssociatedObject.Content, (vm) =>
            {
                if (vm.RequestClose())
                {
                    AssociatedObject.Close();
                }
            });
        }

        void ToMaxOrNormalWindow()
        {
            AssociatedObject.WindowState = AssociatedObject.WindowState == WindowState.Normal ? WindowState.Maximized : WindowState.Normal;
        }
    }
}
